<template>
  <div>
    <van-nav-bar
      title="地址管理"
      left-arrow
      fixed
      placeholder
      @click-left="goBack"
    >
      <template #right>
        <van-icon name="search" size="18" />
      </template>
    </van-nav-bar>
    <van-address-list
      v-model="chosenAddressId"
      :list="addressList"
      default-tag-text="默认"
      @add="addressAdd"
      @edit="addressEdit"
    />
  </div>
</template>
<script>
import { useRouter } from 'vue-router'
import { onMounted, reactive, toRefs } from 'vue'
import { addressList } from '../../network/address'
export default {
  setup () {
    const router = useRouter()
    const state = reactive({
      chosenAddressId: '0',
      addressList: []
    })
    const goBack = () => {
      router.go(-1)
    }
    const init = () => {
      addressList().then(res => {
        console.log(res)
        res.data.forEach(item => {
          state.addressList.push({
            id: item.id,
            name: item.name,
            tel: item.phone,
            address: item.province + item.city + item.county + item.address,
            isDefault: item.is_default === 1
          })
        })
      })
    }
    onMounted(() => {
      init()
    })
    const addressAdd = () => {
      router.push({ path: '/addressedit', query: { type: 'add' } })
    }
    const addressEdit = (value) => {
      router.push({ path: '/addressedit', query: { type: 'edit', id: value.id } })
    }
    return {
      ...toRefs(state),
      goBack,
      addressAdd,
      addressEdit
    }
  }
}
</script>
<style scoped>
</style>
